#include "Handle.h"

namespace syncLib
{

    Handle::Handle()
        :mHandle_(NULL)
    {
    }

    Handle::Handle(Handle& h)
        : mHandle_(h.Detach())
    {
    }

    Handle::Handle(const HANDLE& h)
        : mHandle_(h)
    {
    }

    Handle::~Handle()
    {
        if (mHandle_)
        {
            Close();
        }
    }

    Handle& Handle::operator=(Handle& h)
    {
        if (mHandle_ != h)
        {
            if (NULL != mHandle_)
            {
                Close();
            }

            Attach(h.Detach());
        }

        return *this;
    }

    inline Handle::operator HANDLE() const
    {
        return mHandle_;
    }

    void Handle::Attach(HANDLE h)
    {
        mHandle_ = h;
    }

    inline HANDLE Handle::Detach()
    {
        HANDLE thisValue = mHandle_;

        mHandle_ = NULL;

        return thisValue;
    }

    BOOL Handle::Close()
    {
        BOOL bRet = FALSE;
        if (mHandle_)
        {
            bRet = CloseHandle(mHandle_);

            mHandle_ = NULL;
        }
        return bRet;
    }


};